
export const getWidgetName = (name) => {
  return name + '-widget'
}
export const getRenderName = (widget) => {
  if (widget.category) {
    return widget.type + '-render'
  }
  return widget.type + '-widget'
}
export const deepclone = (obj, map = new WeakMap()) => {
  if (obj && typeof obj === 'object') {
    const isArray = Array.isArray(obj)
    const copyObj = isArray ? [] : {}
    if (map.has(obj)) return map.get(obj)
    map.set(obj, copyObj)
    for (let key in obj) {
      copyObj[key] = deepclone(obj[key], map)
    }
    return copyObj
  } else {
    return obj
  }
}

// 随机生成组件唯一名称
export const getRandomPropName = (widgetType) => {
  let res = widgetType
  for (let i = 0; i < 8; i++) {
    res += Math.floor(Math.random() * 10) + 1
  }
  return res
}

export const saveJSONAsFile = (data, filename) => {
  if (!filename) filename = 'json.json'
  if (typeof data === 'object') {
    data = JSON.stringify(data, undefined, 4)
  }
  var blob = new Blob([data], {
      type: 'text/json'
    }),
    e = document.createEvent('MouseEvents'),
    a = document.createElement('a')
  a.download = filename
  a.href = window.URL.createObjectURL(blob)
  a.dataset.downloadurl = ['text/json', a.download, a.href].join('_')
  e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  a.dispatchEvent(e)
}

export const setMapValueByJSON = (map, json) => {
  map.clear()
  
  const func = (widgetList) => {
    for (let i of widgetList) {
      if (!i.category) {
        map.set(i.options.propName, i)
      } else {
        func(i.cols ?? i.widgetList ?? [])
      }
    }
  }
  func(json)
  return map
}